﻿using BilbilBLL;
using Common;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using Modles.DTO;
using Modles.Models;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace bilbil.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class AccountController : ControllerBase
    {
        IConfiguration _configuration;
        public AccountController(IConfiguration configuration)
        {
            _configuration = configuration;
        }
        [HttpPost]
        [AllowAnonymous]
        public IActionResult Login([FromBody] Login_DTO model)
        {
            AccountService accountService = new AccountService();
            ResponseTool res = accountService.Login(model);
            if (res.code == 200)
            {
                string str = GetToken((UserInfo)res.data);
                Account_DTO account_DTO = new Account_DTO();
                account_DTO.Id = ((UserInfo)res.data).Id;
                account_DTO.Avatar = ((UserInfo)res.data).Avatar;
                account_DTO.Name = ((UserInfo)res.data).Name;
                account_DTO.Signature = ((UserInfo)res.data).Signature;
                account_DTO.Gender = ((UserInfo)res.data).Gender;
                account_DTO.Afos = ((UserInfo)res.data).Afos;
                account_DTO.Jwt = str;
                return new JsonResult(ResponseTool.Succeed(account_DTO));
            }
            return new JsonResult(res);
        }

        private string GetToken(UserInfo user)
        {
            SymmetricSecurityKey ker = new SymmetricSecurityKey(
                //取出私钥
                Encoding.UTF8.GetBytes(_configuration["JwtSettings:SecretKey"])
                );
            SigningCredentials creds = new SigningCredentials(ker, SecurityAlgorithms.HmacSha256);
            Claim[] claims = new Claim[]
          {
                new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString())
          };
            var tokendata = new JwtSecurityToken(
                 issuer: _configuration["JwtSettings:Issuer"],
                //接受者
                audience: _configuration["JwtSettings:Audience"],
                //声明,这里用前面定义的声明数组,这里暂时可以理解为存放用户信息
                claims: claims,
                //设置令牌过期时间,这里参数为30表示30分钟后失效
                expires: DateTime.Now.AddMinutes(30),
                //签名凭证，这里用前面配置的creds签名凭证,用于对JWT签名
                signingCredentials: creds
                );
            return new JwtSecurityTokenHandler().WriteToken(tokendata);
        }
    }
}
